import {getCache,setCache} from './global'
import siteinfo from './siteinfo'

const api = (method,path,param) => {
	return new Promise((resolve, reject) => {
		let apiurl = siteinfo.siteroot + '?i=' + siteinfo.uniacid + '&c=entry&a=wxapp&m=qd_tm&do=api&path=' + path
		let paramObj = Object.assign({token:uni.getStorageSync('token')},param)
		if(method == 'GET' && getApp()){
			//读缓存
			let cache = getCache(path+JSON.stringify(paramObj))
			if(cache){
				resolve(cache)
				return
			}
		}
		uni.showLoading()
		uni.request({
			url: apiurl,
			method : method,
			data: paramObj,
			success: res => {
				if(res.data.code == 200){
					if(method == 'GET' && getApp()){// && process.env.NODE_ENV !== 'development'){//写缓存
						if(path == 'json'){
							let cachetime = 604800 //getApp().globalData.config.cache
							setCache(path+JSON.stringify(paramObj),res.data.data,cachetime)
						}
					}
					if(res.data.msg){
						uni.showToast({
							title: res.data.msg,
							icon: 'success',
							duration: 2000
						})
					}
					if(method != 'GET'){
						setCache('refresh',1)
					}
				}else if(res.data.code == 401){
					let pages = getCurrentPages()
					let page = pages[pages.length - 1]
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					})
					if(page.data.hasOwnProperty('showLogin')){
						uni.$emit('loginClick')
					}else{
						let gotoLogin = getCache('gotoLogin')
						if(!gotoLogin){
							setCache('gotoLogin',1)
							setTimeout(()=>{
								setCache('gotoLogin',0)
								uni.navigateTo({url:'/pages/login'})
							},2000)
						}
					}
				}else if(res.data.code == 404){
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel : false,
						success: function (res) {
							if (res.confirm) {
								let pages = getCurrentPages()
								if(pages.length > 1){
									uni.navigateBack({delta: 1})
								}else{
									uni.switchTab({url:'/pages/tabBar1'})
								}
							}
						}
					})
				}else if(res.data.code == 500){
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel : false
					})
				}
				resolve(res.data.data)
			}
		})
		uni.hideLoading()
	})
}
export default api